package com.csc.controller;

import com.csc.dto.ProductParam;
import com.csc.entity.Products;
import com.csc.entity.ProductTypes;
import com.csc.service.ProductService;
import com.csc.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
@CrossOrigin
public class ProductController {

    @Autowired
    private ProductService productManagementService;

    // 产品相关接口
    @PostMapping("/list")
    public List<Products> listProducts(@RequestBody ProductParam productParam) {
        return productManagementService.listProducts(productParam);
    }

    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addProduct(@RequestBody Products product) {
        Map<String, Object> response = new HashMap<>();
        try {
            String result = productManagementService.addProduct(product);
            response.put("success",  "success".equals(result));
            response.put("message",  result);
            return response;
        } catch (Exception e) {
            response.put("success",  false);
            response.put("message",  "添加失败: " + e.getMessage());
            return response;
        }
    }

    @GetMapping("/detail")
    public Products getProductDetail(@RequestParam Integer productId) {
        return productManagementService.getProductDetail(productId);
    }

    @PostMapping("/update")
    public String updateProduct(@RequestBody Products products) {
        return productManagementService.updateProduct(products);
    }

    @DeleteMapping("/delete")
    public String deleteProduct(@RequestParam Integer productId) {
        return productManagementService.deleteProduct(productId);
    }

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        System.out.println(" 上传图片");
        return FileUtil.upload(file);
    }

    // 产品类型相关接口
    @GetMapping("/type/list")
    public List<ProductTypes> listProductTypes() {
        return productManagementService.listProductTypes();
    }
}